//
//  String+Emoji.swift
//  Utility
//
//  Created by 于虎拴 on 2023/4/3.
//

import Foundation

public extension Character {
  /// 简单的emoji是一个标量，以emoji的形式呈现给用户
  var isSimpleEmoji: Bool {
    guard let firstScalar = unicodeScalars.first else { return false }
    return firstScalar.properties.isEmoji && firstScalar.value > 0x238C
  }
  
  /// 检查标量是否将合并到emoji中
  var isCombinedIntoEmoji: Bool {
    return unicodeScalars.count > 1 && unicodeScalars.first?.properties.isEmoji ?? false
  }
  
  /// 是否为emoji表情
  /// - Note: http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
  var isEmoji: Bool{
    return isSimpleEmoji || isCombinedIntoEmoji
  }
}

public extension String {
  /// 是否为单个emoji表情
  var isSingleEmoji: Bool {
    return count == 1 && containsEmoji
  }
  
  /// 包含emoji表情
  var containsEmoji: Bool {
    return contains { $0.isEmoji }
  }
  
  /// 只包含emoji表情
  var containsOnlyEmoji: Bool {
    return !isEmpty && !contains { !$0.isEmoji }
  }
  
  /// 提取emoji表情字符串
  var emojiString: String {
    return emojis.map { String($0) }.reduce("", +)
  }
  
  /// 提取emoji表情数组
  var emojis: [Character] {
    return filter { $0.isEmoji }
  }
  
  /// 提取单元编码标量
  var emojiScalars: [UnicodeScalar] {
    return filter { $0.isEmoji }.flatMap{ $0.unicodeScalars }
  }
}
